var info, jishu = 0, AllCount = 0, tmpPath = null, imglistIndex = 0, img4list = [], nowCanvas = null;
import JCAPI from "../../utils/JCAPI/JCAPI";
import { consoleWXML } from "../ruKuDaYin/ruKuDaYin";
const app = getApp()
async function consoleIMGList(imglist, nowPrint, canvas) {
  AllCount = 0, imglistIndex = 0, img4list = [], nowCanvas = null
  return new Promise((reslove, reject) => {
    //console.log(params);
    if (nowPrint == null) {
      reslove(null)
    }
    img4list = imglist
    for (let index = 0; index < imglist.length; index++) {
      const element = imglist[index];
      AllCount += element.count
      wx.request({
        url: 'https://127.0.0.1:10270/api/printLog'
          + '?imgurl=' + element.imgurl
          + '&count=' + element.count
          + '&userid=' + app.globalData.userId,
        method: 'POST'
      })
    }
    nowCanvas = canvas
    console.log(AllCount);
    console.log("consoleIMG start");
    JCAPI.didReadPrintCountInfo(function (res) {
      console.log("didReadPrintCountInfo start");
      console.log(res);
      jishu+=res.count;
      imglistIndex++;
      getApp().globalData.printingCount = jishu
      console.log(getApp().globalData.printingCount);
      if (AllCount == jishu) {
        console.log("bluetoothEnd start");
        jishu = 0
        AllCount = 0
        tmpPath = null
        imglistIndex = 0
        img4list = []
        return reslove("打印完成")
      }
    });
    JCAPI.didReadPrintErrorInfo(function (params) {
      console.log(params);
      return reslove(params.msg)
    });
    JCAPI.startJob(1, 3, AllCount, function () {
      console.log("startJob start");
      //startPrinting2();
      return reslove(startPrintingList())
    });
  })
}
function startPrintingList() {
  if (img4list.length > imglistIndex) {
    console.log("startPrinting start");
    JCAPI.startDrawLabel('drawCanvas', nowCanvas, 50, 80, 0);
    //JCAPI.drawText("element.value",element.x,element.y,element.fontSize,element.rotation,element.options);
    //JCAPI.drawText("element.value",4,7,3,0,null);
    imgdownload(img4list[imglistIndex].imgurl).then((res)=>{
      tmpPath = res
      console.log(tmpPath);
      var width = Math.ceil(Number((Number(tmpPath[0]) / 8).toFixed(1)))
      var height = Math.ceil(Number((Number(Number(tmpPath[1]) / 8).toFixed(1))))
      console.log(width + "   " + height);
      console.log(tmpPath[2]);
      if (height > 70) {
        console.log("if");
        var Scale = 70 / height
        var widthScale = Math.ceil(Number((width * Scale).toFixed(1)))
        var width4MarginLeft = (50 - widthScale) / 2
        JCAPI.drawImage(tmpPath[2], width4MarginLeft, 0, widthScale, 70, 0);
      } else {
        console.log("else");
        var width4MarginLeft = (50 - width) / 2
        console.log(width4MarginLeft);
        JCAPI.drawImage(tmpPath[2], width4MarginLeft, 1, width, height, 0);
      }
      JCAPI.endDrawLabel(function () {
        JCAPI.print(img4list[imglistIndex].count, function () {
          console.log(imglistIndex);
          startPrintingList();
        });
      });
    })
    
  }
}

async function linkPrint() {
  bluetoothStart();
  return new Promise((reslove, reject) => {
    JCAPI.scanedPrinters((result) => {
      wx.hideLoading();
      console.log(result);
      var arr = [];
      for (let index = 0; index < result.length; index++) {
        const element = result[index];
        if (element.localName == "" || element.localName == null) {
          //console.log(index);
        }
        else if (element.name == "未知设备") {
          //console.log(index);
        }
        else {
          arr.push(element)
        }
      }
      console.log(arr);
      reslove(arr)
    })
  })

}
function bluetoothStart() {
  wx.getSetting({
    success(res) {
      //console.log(res.authSetting)
      //判断是否有'scope.bluetooth'属性
      if (res.authSetting.hasOwnProperty('scope.bluetooth')) {
        //'scope.bluetooth'属性存在，且为false
        if (!res.authSetting['scope.bluetooth']) {
          //弹窗授权
          wx.openSetting({
            success(res) {
              //console.log(res.authSetting)
              wx.openBluetoothAdapter({
                success: function (res) {
                  console.log('初始化蓝牙适配器成功')
                  //console.log(res);
                  //页面日志显示
                  info = '初始化蓝牙适配器成功'
                },
                fail: function (res) {
                  console.log(res);
                  info = res.errMsg
                }
              })
            }
          })
        }
        else {
          wx.openBluetoothAdapter({
            success: function (res) {
              console.log('初始化蓝牙适配器成功')
              console.log(res);
              //页面日志显示
              info = '初始化蓝牙适配器成功'
            },
            fail: function (res) {
              console.log(res);
              wx.authorize({
                scope: 'scope.bluetooth',
                success(res) {
                  // 用户已经同意小程序使用手机蓝牙功能，后续调用 蓝牙 接口不会弹窗询问
                  console.log(res.authSetting)
                  wx.openBluetoothAdapter({
                    success: function (res) {
                      console.log('初始化蓝牙适配器成功')
                      //页面日志显示
                      info = '初始化蓝牙适配器成功'
                    },
                    fail: function (res) {
                      console.log(res);
                      info = res.errMsg
                    }
                  })
                }
              })
            }
          })
        }
      }
      else {
        //'scope.bluetooth'属性不存在，需要授权
        wx.authorize({
          scope: 'scope.bluetooth',
          success(res) {
            // 用户已经同意小程序使用手机蓝牙功能，后续调用 蓝牙 接口不会弹窗询问
            console.log(res.authSetting)
            wx.openBluetoothAdapter({
              success: function (res) {
                console.log('初始化蓝牙适配器成功')
                //页面日志显示
                // info = '初始化蓝牙适配器成功'
                getApp().globalData.nowPrint = []
              },
              fail: function (res) {
                console.log(res);
                info = res.errMsg
              }
            })
          }
        })
      }
    }
  })
}
function bluetoothEnd() {
  wx.closeBluetoothAdapter({
    success: function (res) {
      console.log('关闭蓝牙适配器成功')
      //页面日志显示
      info = '关闭蓝牙适配器成功'
    },
    fail: function (res) {
      console.log(res);
      //bluetoothEnd();
    }
  })
}
async function imgdownload(url) {
  return new Promise((reslove, reject) => {
    wx.downloadFile({
      url: url,
      success: function (res) {
        // 下载成功后将文件转为临时路径
        if (res.statusCode === 200) {
          // wx.setStorageSync('tempFilePath', res.tempFilePath);
          console.log(res.tempFilePath);
          var urlList = url.split("/")
          var urlNew = urlList[urlList.length-1].replace(".jpg","")
          console.log(urlNew);
          var req = wx.request({
            url: 'https://127.0.0.1:10270/api/imageSize?url='+urlNew,
            method: 'get',
            success: (result) => {
              console.log(result);
              if (result.statusCode == 200) {
                var size = [result.data[0], result.data[1], res.tempFilePath]
                reslove(size)
              }
            },
            fail:()=>{
              req.abort()
            }
          })
          // reslove(res.tempFilePath)
        }
      }
    });
  })
}
module.exports = {
  consoleIMGList: consoleIMGList,
  linkPrint: linkPrint,
  bluetoothEnd: bluetoothEnd
};